package cc.yiueil.service.impl;

import cc.yiueil.entity.OrderEntity;
import cc.yiueil.entity.ProductEntity;
import cc.yiueil.feign.ProductServiceRemote;
import cc.yiueil.service.OrderService;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    // 使用OpenFeign客户端进行调用
    @Autowired
    ProductServiceRemote productServiceRemote;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderBlockHandler")
    @Override
    public OrderEntity createOrder(Long productId, Long userId) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setId(1L);
        orderEntity.setProductId(productId);
        orderEntity.setUserId(userId);
        orderEntity.setCreateTime(LocalDateTime.now());
        // 计算总价 调用远程过程调用获取商品的价格
        ProductEntity productEntity = getProductRemote2(productId);
        orderEntity.setPrice(productEntity.getPrice());
        return orderEntity;
    }

    @Override
    public OrderEntity testOrder() {
        OrderEntity orderEntity;
        try (Entry entry = SphU.entry("testRule")) {
            orderEntity = new OrderEntity();
            orderEntity.setId(1L);
            orderEntity.setProductId(1L);
            orderEntity.setUserId(1L);
            orderEntity.setCreateTime(LocalDateTime.now());
        } catch (BlockException e) {
            throw new RuntimeException(e);
        }
        return orderEntity;
    }

    public OrderEntity createOrderBlockHandler(Long productId, Long userId, BlockException blockException) {
        blockException.printStackTrace();
        return new OrderEntity();
    }

    private ProductEntity getProductRemote(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = serviceInstance.getUri() + "/getProduct?id=" + productId;
        log.info("远程调用: {}", url);
        return restTemplate.getForObject(url, ProductEntity.class);
    }

    private ProductEntity getProductRemote2(Long productId) {
        return productServiceRemote.getProduct(productId);
    }
}
